package com.kaka.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

/*
 * joda类的使用
 * DateFormatUtils类的使用
 * DateUtils类的使用
 */
public class DateUtil {
    private static final Pattern TIME_P = Pattern.compile("(\\d+)时(\\d+)分(\\d+)秒(\\d+)毫秒");
    public static SimpleDateFormat dmy_hm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	static String[] parsePatterns = { "yyyy-MM-dd", "yyyy/MM/dd" };
	private static Log log = LogFactory.getLog(DateUtil.class);
	
	public static String formatDateYMDToStr(Date date) {
	    if(date == null)
	        return null;
		try {
			return dmy_hm.format(date);
		} catch (Exception e) {
			log.debug("DateUtil.formatDateYMDToStr():" + e.getMessage());
			return null;
		}

	}

	/*
	 * 得到当前日期字符串 格式（yyyyMMdd）
	 */
	public static String getDate() {
		return DateFormatUtils.format(new Date(), "yyyyMMdd");
	}

	/*
	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if(null==date)
			return formatDate;

		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/*
	 * 天数相加
	 */
	public static Date addDay(Date date, int d) {
		return DateUtils.addDays(date, d);
	}

	/*
	 * 月份相加
	 */
	public static Date addMonths(Date date, int m) {
		return DateUtils.addMonths(date, m);
	}

	/*
	 * 日期型字符串转化为日期 格式（"yyyy-MM-dd","yyyy/MM/dd"）
	 */
	public static Date parseDate(String str,String... pattern) throws ParseException {
		return DateUtils.parseDate(str, pattern);
	}
	
	/**
	 * 
	 * @Title: toMillisecond 
	 * @Description: 将 xx时xx分xx秒xx毫秒 化成 毫秒
	 * @param time
	 * @return  Long
	 */
	public static Long toMillisecond(String time){
	    String orgTime = time;
	    if(StringUtils.isEmpty(time))
	        return null;
        if(!time.contains("分"))
            time = "0分" + time;
	    if(!time.contains("时"))
	        time = "0时" + time;
	    if(!time.contains("毫秒"))
	        time = time + "毫秒";
	    Matcher m = TIME_P.matcher(time);
	    if(m.matches()){
	        Long l = 0L;
	        String h = m.group(1);
            l = l + Long.parseLong(h) * 60 * 60 * 1000;
	        String min = m.group(2);
	        l = l + Long.parseLong(min) * 60 * 1000;
	        String s = m.group(3);
	        l = l + Long.parseLong(s) * 1000;
	        String ms = m.group(4);
	        l = l + Long.parseLong(ms);
	        return l;
	    } else {
	        throw new IllegalArgumentException("无效的时间格式：" + orgTime);
	    }
	}

	public static Timestamp getTimestamp(Date...dates){
	    if(dates == null || dates.length == 0){
	        return new Timestamp(new Date().getTime());
	    } else {
	        return new Timestamp(dates[0].getTime());
	    }
	}

	/**
	 * 比较两个日期相差的天数
	 *
	 */
	public static int getDiffDays(String date1,String date2){
		int margin;
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			ParsePosition pos = new ParsePosition(0);
			ParsePosition pos1 = new ParsePosition(0);
			Date dt1 = sdf.parse(date1,pos);
			Date dt2 = sdf.parse(date2,pos1);
			long l = dt1.getTime() - dt2.getTime();
			margin = (int)(l / (24 * 60 * 60 * 1000));
			return margin;
		} catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	
	public static int getDiffDays(Date dt1,Date dt2){
        int margin;
        try{
            long l = dt1.getTime() - dt2.getTime();
            margin = (int)(l / (24 * 60 * 60 * 1000));
            if(margin == 0){
                margin = dt1.getDay() - dt2.getDay();
            }
            return margin;
        } catch(Exception e){
            e.printStackTrace();
            return 0;
        }
    }
	
	public static int getDiffYeas(Date dt1,Date dt2){
		int margin;
        try{
        	margin = dt1.getYear() - dt2.getYear();
            return margin;
        } catch(Exception e){
            e.printStackTrace();
            return 0;
        }
	}
	
	/**
	 * 
	 * @Title: isAfter 
	 * @Description: d2 在 d1 后则返回true
	 * @param d1
	 * @param d2
	 * @return  boolean
	 */
	public static boolean isAfter(Date d1, Date d2){
	    if(d1 != null && d2 != null)
	        return d1.before(d2);
	    else
	        return false;
	}
	
	public static Date splitDay(Date d){
	    Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
	}

	
    /** 
     * 获取某年第一天日期 
     * @param year 年份 
     * @return Date 
     */  
    public static Date getYearFirst(int year){  
        Calendar calendar = Calendar.getInstance();  
        calendar.clear();  
        calendar.set(Calendar.YEAR, year);  
        Date currYearFirst = calendar.getTime();  
        return currYearFirst;  
    }  
      
    /** 
     * 获取某年最后一天日期 
     * @param year 年份 
     * @return Date 
     */  
    public static Date getYearLast(int year){  
        Calendar calendar = Calendar.getInstance();  
        calendar.clear();  
        calendar.set(Calendar.YEAR, year);  
        calendar.roll(Calendar.DAY_OF_YEAR, -1);  
        Date currYearLast = calendar.getTime();  
          
        return currYearLast;  
    } 
    
    
	public static void main(String[] args){
        // TODO Auto-generated method stub
        String favoriteRaces = "aaa,vvv,";
        if(!StringUtils.isEmpty(favoriteRaces)){
            favoriteRaces = favoriteRaces.substring(0, favoriteRaces.length()-1);
        }
        System.out.println(favoriteRaces);
	}
}
